const connection = require('../app/batabase');


class FileService {
   //将图像信息保存到数据库
   async createAvatar (filename, mimetype, size, userId) {
     try {
      const statement = `INSERT INTO avatar (filename, mimetype, size, user_id) VALUES (?, ?, ?, ?);`;
      await connection.execute(statement, [filename, mimetype, size, userId]);
     } catch (err) {
        console.log(err)
     }
   }

   //查看头像接口
   async getAvatarByUserId (id) {
       const statement = `SELECT * FROM avatar WHERE user_id = ?;`;
       const [result] = await connection.execute(statement, [id]); 
       return result[result.length - 1];

   }

   //将头像地址存储到user表的avatar字段中
   async updateAvatarUrlById(avatarUrl, userId) {
      const statement = `UPDATE user SET avatar_url = ? WHERE id = ?;`;
      const [result] = await connection.execute(statement, [avatarUrl, userId]);
      return result;
   }


   //上传动态的配图
   async createPicture(filename, mimetype, size, userId, momentId) {
     try {
      const statement = `INSERT INTO file (filename, mimetype, size, moment_id, user_id) VALUES (?, ?, ?, ?, ?);`;
      await connection.execute(statement, [filename, mimetype, size, momentId, userId]);
     } catch (err) {
        console.log(err);
     }

   }

   //动态的配图服务
   async getFileByFilename (filename) {
      const statement = `SELECT * FROM file WHERE filename = ?;`;
      const [result] = await connection.execute(statement, [filename]); 
      return result[0];
  }
}

module.exports = new FileService();